package handlers

import (
	"com-man-sys/cache"
	"com-man-sys/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var com []models.Com
	redid_key := "com_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redid_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&com).Debug()
		jsonData, _ := json.Marshal(com)
		cache.Rdb.Set(cache.Ctx, redid_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &com)
	}

	var count int64
	models.DB.Model(&models.Com{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"com":   com,
		},
	})
	return

}

func Comment(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.User{
		Username: username,
		Password: password,
	}

	models.DB.Create(&data).Debug()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
